#!/bin/bash

# iOS地理位置权限修复脚本
# 作用：修复iOS端地理位置权限配置问题

echo "🗺️ 开始修复iOS地理位置权限配置..."
echo "======================================"

# 获取脚本所在目录（项目根目录）
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo "📁 当前目录: $(pwd)"
echo "⏰ 开始时间: $(date)"

# 检查是否为 Flutter 项目
if [ ! -f "pubspec.yaml" ]; then
    echo "❌ 错误：当前目录不是 Flutter 项目！"
    read -p "按任意键退出..." -n1 -s
    exit 1
fi

echo "✅ 检测到 Flutter 项目"

# 显示项目信息
PROJECT_NAME=$(grep "^name:" pubspec.yaml | cut -d' ' -f2 2>/dev/null || echo "unknown")
echo "📄 项目名称: $PROJECT_NAME"

echo ""
echo "🚨 问题分析："
echo "   iOS端位置权限配置和请求问题"
echo "   需要重新生成iOS项目配置"
echo ""

echo "🔍 将执行以下操作："
echo "   1. 🧹 清理Flutter和iOS项目"
echo "   2. 🔄 重新生成iOS配置"
echo "   3. 📦 重新安装CocoaPods依赖"
echo "   4. 🎯 验证权限配置"
echo ""

echo "🚀 开始自动修复..."
echo ""

# 步骤 1: 清理项目
echo "🧹 步骤 1/4: 清理项目..."
echo "----------------------------------------"

# 清理 Flutter 缓存
flutter clean

# 清理 iOS 构建文件
cd ios
rm -rf build/
rm -rf .symlinks/
rm -rf Pods/
rm -f Podfile.lock
rm -rf ~/Library/Developer/Xcode/DerivedData/*Runner* 2>/dev/null || true

echo "✅ 项目清理完成"
cd ..

echo ""

# 步骤 2: 重新生成配置
echo "🔄 步骤 2/4: 重新生成iOS配置..."
echo "----------------------------------------"

# 重新获取 Flutter 依赖
flutter pub get

# 强制重新生成 iOS 配置
flutter build ios --config-only --debug

echo "✅ iOS配置重新生成完成"

echo ""

# 步骤 3: 重新安装 CocoaPods 依赖
echo "📦 步骤 3/4: 重新安装CocoaPods依赖..."
echo "----------------------------------------"
cd ios
pod install --repo-update
cd ..

echo "✅ CocoaPods依赖安装完成"

echo ""

# 步骤 4: 验证配置
echo "🎯 步骤 4/4: 验证权限配置..."
echo "----------------------------------------"

echo "检查Info.plist中的权限配置..."

if grep -q "NSLocationWhenInUseUsageDescription" ios/Runner/Info.plist; then
    echo "✅ NSLocationWhenInUseUsageDescription 已配置"
else
    echo "❌ NSLocationWhenInUseUsageDescription 缺失"
fi

if grep -q "NSLocationAlwaysAndWhenInUseUsageDescription" ios/Runner/Info.plist; then
    echo "✅ NSLocationAlwaysAndWhenInUseUsageDescription 已配置"
else
    echo "❌ NSLocationAlwaysAndWhenInUseUsageDescription 缺失"
fi

if grep -q "AMapApiKey" ios/Runner/Info.plist; then
    echo "✅ 高德地图API Key 已配置"
else
    echo "❌ 高德地图API Key 缺失"
fi

echo ""
echo "🎉 iOS地理位置权限配置修复完成！"
echo "======================================"

echo "📝 修复总结："
echo "   ✅ 重新清理了项目"
echo "   ✅ 重新生成了iOS配置"
echo "   ✅ 重新安装了CocoaPods依赖"
echo "   ✅ 验证了权限配置"

echo ""
echo "🍎 现在可以重新运行项目："
echo "   方法 1: flutter run"
echo "   方法 2: 在 Xcode 中打开 ios/Runner.xcworkspace"

echo ""
echo "💡 重要提示："
echo "   - 首次运行时会弹出位置权限请求"
echo "   - 如果权限被拒绝，需要到系统设置中手动开启"
echo "   - 确保选择了正确的设备/模拟器"

echo ""
echo "🚨 如果仍然没有权限弹窗，可能需要："
echo "   1. 完全删除应用后重新安装"
echo "   2. 在设备设置中重置位置权限"
echo "   3. 检查Xcode中的代码签名配置"

echo ""
echo "⏰ 完成时间: $(date)"
echo "======================================"

# 询问是否立即测试
echo ""
read -p "是否现在立即测试运行？(Y/n): " TEST_RUN
if [[ ! $TEST_RUN =~ ^[Nn]$ ]]; then
    echo "🚀 正在启动 Flutter 运行..."
    flutter run --debug
fi

# 等待用户按键后关闭
echo ""
echo "按任意键关闭窗口..."
read -n1 -s
